<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "c196266f837d14e0b693f961bee37b66");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid(); //验证
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

      	//extract post data
		if (!empty($postStr)){
                
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";             
				if(!empty( $keyword ))
                {
              		$msgType = "text";
					$keyword = strtoupper($keyword);
					$contentStr = $this->checkInput($keyword);
					if(empty($contentStr)) $contentStr = "欢迎您访问志彦公共微信\n回复'C' 联系我们。\n回复'S' 服务内容。\n更多惊喜请您访问 http://www.zylinkus.com";
                	
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                }else{
                	echo "Input something...";
                }

        }else {
        	echo "";
        	exit;
        }
    }
	
	//通过输入的信息显示不一样的
	private function checkInput($_input) {
		$_lang = array("C"=>"上海志彦文化\n网站:www.zylinkus.com\nTel:+86 21 62162769 \nFax:+86 21 62162769\nEmail:zylinkus.com@gmail.com","S"=>"网站系统开发\n电子商务系统开发\n手机移动互联网\n<a href='http://i.youku.com/u/id_UNTAzODUzMzY0'>演员模特演艺</a>\n回复'C' 联系我们。");
		
		return $_lang[$_input];
		
	}
		
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}
//END